<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Validation;
use Illuminate\Support\Facades\Auth;
use App\User;

class LoginController extends Controller
{

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
//    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
    }

    public function login(Request $request){

        return view('login.login');
    }

    /*
     *用户登录操作
     */
    public function postLogin(Request $request){
        $name = $request->input('name');
        $password = $request->input('password');
        if(empty($name)){
            return $this->getMessage(1,'用户名不能为空');
        }
        if(empty($password)){
            return $this->getMessage(2,'密码不能为空');
        }
        $userName = $this->validateUserName($name);

        if (Auth::attempt([$userName => $name,'is_admin'=>1, 'password' => md5($password)],true)) {
            return $this->getMessage(0,'登录成功');
        }
        return $this->getMessage(3,'用户名或密码错误');
    }

    /*
     * 退出登录
     */
    public function logout(Request $request){
        Auth::logout();
        return redirect('login');
    }
    /*
     * 用户信息验证
     */
    private function validateUserName($name){
        $type = '';
        $reg_mobile  = '/^1[3|4|5|6|7|8|9]{1}\d{9}$/';
        $reg_email  = '/^(\w|\d)+([-+.](\w|\d)+)*@(\w|\d)+([-.](\w|\d)+)*\.\w+([-.]\w+)*/';
        if(preg_match($reg_email,$name)){
            $type = 'email';
        }elseif(preg_match($reg_mobile,$name)){
            $type = 'mobile';
        }else{
            $type = 'name';
        }
        if(empty($type)){
            return false;
        }
        return $type;
    }

}